package org.example.service.impl;

import org.example.dao.SchedulesDao;
import org.example.domain.Schedules;
import org.example.domain.Student;
import org.example.service.INotSupportService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.annotation.Resource;

import static java.lang.Thread.sleep;

@Service
public class NotSupportServiceImpl implements INotSupportService {


    @Resource
    private SchedulesDao schedulesDao;

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public int test() throws InterruptedException {
        TransactionSynchronizationManager.registerSynchronization(
                new TransactionSynchronization() {
                    @Override
                    public void suspend() {
                        // 事务挂起时执行
                        System.out.println("Transaction suspended");
                    }

                    @Override
                    public void resume() {
                        // 事务恢复时执行
                        System.out.println("Transaction resumed");
                    }

                    @Override
                    public void beforeCommit(boolean readOnly) {
                        // 事务提交前执行
                        System.out.println("Before commit");
                    }

                    @Override
                    public void beforeCompletion() {
                        // 事务完成前执行
                        System.out.println("Before completion");
                    }

                    @Override
                    public void afterCommit() {
                        // 事务提交后执行
                        System.out.println("After commit");
                    }

                    @Override
                    public void afterCompletion(int status) {
                        // 事务完成后执行
                        System.out.println("After completion, status: " + (status == STATUS_COMMITTED ? "Committed" : "Rolled back"));
                    }
                });
        int n = 0;
        for (int i = 0; i < 1000; i++) {
            Schedules schedules = new Schedules();
            schedules.setScheduleid(i);
            schedules.setDescription("test" + i);
            n += schedulesDao.updateByPrimaryKeySelective(schedules);
            sleep(500);
        }

        return n;
    }
}
